import { NextRequest, NextResponse } from 'next/server';
import xss from 'xss';
import { createClient } from "@/utils/supabase/server";
import { scanAndSyncJetbrainsInstances } from '@/lib/jetbrains-scanner';

async function handleUpdateStatus(id: string, status: string, supabase: ReturnType<typeof createClient>) {
    const filteredId = xss(id);
    const filteredStatus = xss(status);

    const currentDate = new Date();
    const formattedDate = currentDate.toISOString().replace('T', ' ').substring(0, 19);

    // 首先获取当前记录的availability值
    const { data: currentRecord, error: fetchError } = await supabase
        .from("jetbrains")
        .select("availability")
        .eq("id", Number(filteredId))
        .single();

    if (fetchError) {
        console.error('Error fetching current record:', fetchError);
        return;
    }

    // 当前availability值，如果为null则设为环境变量中的初始值
    const initialScore = parseInt(process.env.INITIAL_AVAILABILITY_SCORE || '100');
    const currentAvailability = currentRecord?.availability ?? initialScore;

    if (filteredStatus === "0") {
        // 状态为0时，availability减1
        const newAvailability = currentAvailability - 1;
        
        if (newAvailability <= 0) {
            // 如果availability降到0或以下，删除该记录
            await supabase
                .from("jetbrains")
                .delete()
                .eq("id", Number(filteredId));
            console.log(`Deleted record ${filteredId} due to availability reaching 0`);
        } else {
            // 否则更新availability
            await supabase
                .from("jetbrains")
                .update({
                    updated_at: formattedDate,
                    availability: newAvailability,
                })
                .eq("id", Number(filteredId))
                .select();
        }
    }

    if (filteredStatus === "1") {
        // 状态为1时，availability加1
        const newAvailability = currentAvailability + 1;
        
        await supabase
            .from("jetbrains")
            .update({
                updated_at: formattedDate,
                availability: newAvailability
            })
            .eq("id", Number(filteredId))
            .select();
    }
}

export async function GET(req: NextRequest) {
    const { searchParams } = new URL(req.url);
    const id = searchParams.get('id');
    const status = searchParams.get('status');
    const supabase = createClient();

    // 参数都不存在时，返回ok
    if (!id && !status) {
        return NextResponse.json({ message: 'error' }, { status: 400 });
    }

    // 只有一个参数存在时，返回error
    if (!id || !status) {
        if(status && status === 'update') {
            await scanAndSyncJetbrainsInstances(supabase);
            return NextResponse.json({ message: '处理成功.' });
        } else {
            return NextResponse.json({ message: 'error' }, { status: 400 });
        }
    }

    await handleUpdateStatus(id, status, supabase);
    // 过滤成功，返回yes
    return NextResponse.json({ message: '更新成功！', id });
}
